<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of RegisterForm
 *
 * @author dung3625@gmail.com
 * @date 01/03/2014
 */
class RegisterForm extends CFormModel{
    public $username;
    public $password;
    public $email;
    public $name;
    public $cpassword;
    public $mobile;
    public $accept;
    public $sale_id;
    public $activate_status;
    public $activate_key;

    private $_identity;
    
        public function rules()
	{
		return array(
			//email, username, password, cpassword are required
			array('email, username, password, cpassword, name, mobile, accept', 'required'),
			//email, username needs to be check
			array('email, username', 'authenticate'),
                                                            //name and username
                                                          array('name, username', 'length', 'min' => 4, 'max'=>20, 
                                            'tooShort'=>Yii::t("translation", "{attribute} is too short."),
                                            'tooLong'=>Yii::t("translation", "{attribute} is too long.")),                    
                                                            //check password 
                                                          array('password', 'length', 'min' => 6, 'max'=>20, 
                                            'tooShort'=>Yii::t("translation", "{attribute} is too short."),
                                            'tooLong'=>Yii::t("translation", "{attribute} is too long.")),
                                                          //cpassword needs to be authenticate
                                                          
//                                                        array('password, cpassword', 'check'),
                                                          array('cpassword', 'compare', 'compareAttribute'=>'password' , 'on'=>'register'),
                                                          //Mobile
                                                          array('mobile','match', 'pattern'=>'#^[0-9]+$#', 'message'=>'Only the following characters are allowed: 0-9', 'on'=>'register' ),
                                                          //accpet needs to be a boolean
//                                                          array('accept', 'boolean'),
                                                          
		);
	}
        public function attributeLabels()
	{
                    return array(
			'accept'=>'I accept the User Agreement',
		);
	}
        public function check()
	{
                                        if ($this->password !== $this->cpassword) {
                                            $this->addError('cpassword','Repeat password is incorrect.');
                                        }	
        }

        public function authenticate($attribute,$params) {
                                       if(!$this->hasErrors())
		{
			$this->_identity=new RegisterIdentity($this->email,  $this->username);
                                                           
			if(!$this->_identity->authenticate())
				$this->addError('username','Username or Email already in use.');
		}	
	}
        public function register() {
            if (!$this->accept) {
                $this->addError('accept','You must accept the User Agreement.');
                return FALSE;
             }
            if($this->_identity===null)
	{
	$this->_identity=new RegisterIdentity($this->email,  $this->username);
	$this->_identity->authenticate();
	}
            if($this->_identity->errorCode===RegisterIdentity::ERROR_NONE)
	{
                //update to database
                     try{
                        $connection=Yii::app()->db;   // assuming you have configured a "db" connection
                        //mỗi account được tạo 1 salepoint
//                        $sql = "INSERT INTO os_salepoint() VALUE()"; //tạo salepoint rỗng
//                        $connection->createCommand($sql)->query();
//                        //lấy id của salepoint vừa tạo save vào os_users
//                        $rows_salepoint = $this->getSalePointDatabase();
                        $this->sale_id = 0;
                        
                        $query="INSERT INTO os_users(username,password,role,email,name,mobile,sale_id, activate_status, activate_key) 
                            VALUE('{$this->username}','{$this->password}','1','{$this->email}','{$this->name}','{$this->mobile}','{$this->sale_id}','{$this->activate_status}','{$this->activate_key}')";
                        $connection->createCommand($query)->query();
                        return true;
                    }catch(Exception $e){}
	}
            else
	return false;
        }
        public function getSalePointDatabase() {
            try {
                $connetion=Yii::app()->db;
                $sql = "SELECT * FROM os_salepoint ORDER BY id DESC";
                $command = $connetion->createCommand($sql);
                $data = $command->query();
                $rows_salepoint = array();
                while ($row = $data->read()) {
                    $rows_salepoint[] = $row;
                }
                return $rows_salepoint;
        }  catch (Exception $e) {
            echo $e;
            return FALSE;
        }}
        public function getUserDatabase($email) {
            try {
            $connetion = Yii::app()->db;
            $sql = "SELECT * FROM os_users WHERE email = '{$email}'";
            $command = $connetion->createCommand($sql);
            $data =$command->query();
            $row_users = array();
            while ($row = $data->read()) {
                $row_users[] = $row;
            }
            if (!empty($row_users)) {
                return $row_users;
            }
         else {
                return FALSE;
            }
        }  catch (Exception $e) {
            echo $e;
        }
        }
        public function activate($email) {
            try {
                $connection = Yii::app()->db;
                $sql = "UPDATE os_users as a
            SET a.activate_status = '{$this->activate_status}'
                        WHERE a.email = '{$email}'";
                $command = $connection->createCommand($sql)->query();
                return true;
        }  catch (Exception $e){
            echo $e;
        }
        }
        public function checkActivate($email,$key) {
            try {
            $connetion = Yii::app()->db;
            $sql = "SELECT * FROM os_users WHERE email = '{$email}' AND activate_key = '{$key}'";
            $command = $connetion->createCommand($sql);
            $data =$command->query();
            $row_users = array();
            while ($row = $data->read()) {
                $row_users[] = $row;
            }
            if (!empty($row_users)) {
                return true;
            }
         else {
                return FALSE;
            }
        }  catch (Exception $e) {
            echo $e;
        }
        }

}

